/**
 * Created by yan_my on 2016/12/9.
 */
import com.sun.org.apache.regexp.internal.RE;

import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.MimeMessage;
import javax.mail.Message;

public class ReceiveMail {

    public static Message[] Receive() throws Exception{

        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "pop3");
        props.setProperty("mail.pop3.port", "110");
        props.setProperty("mail.pop3.host", "pop3.163.com");

        Session session = Session.getInstance(props);
        Store store = session.getStore("pop3");
        store.connect("xiaoyuqwe@sina.com","123456789");

        Folder folder = store.getFolder("INBOX");
        folder.open(Folder.READ_ONLY);

        Message[] messages = folder.getMessages();

        folder.close(true);
        store.close();

        return messages;
    }

    public static StringBuffer mailReceiver(Message m) throws MessagingException,IOException{

                MimeMessage msg = (MimeMessage) m;
                StringBuffer content = new StringBuffer(30);
                getMailTextContent(msg,content);
                return content;

    }

    public static void getMailTextContent(Part part,StringBuffer content) throws MessagingException, IOException{
        boolean isContainTextAttach = part.getContentType().indexOf("name")>0;
        if (part.isMimeType("text/*") && !isContainTextAttach) {
            content.append(part.getContent().toString());
        } else if (part.isMimeType("message/rfc822")) {
            getMailTextContent((Part)part.getContent(),content);
        } else if (part.isMimeType("multipart/*")) {
            Multipart multipart = (Multipart) part.getContent();
            int partCount = multipart.getCount();
            for (int i = 0; i < partCount; i++) {
                BodyPart bodyPart = multipart.getBodyPart(i);
                getMailTextContent(bodyPart,content);
            }
        }
    }

    public static void main(String[] args) throws Exception{
        Message[] messages = ReceiveMail.Receive();
        boolean isLove = false;
        int num = messages.length;
        try {
            if (mailReceiver(messages[num - 1]).indexOf("yes") != -1) {
                isLove = true;
            }
        }catch(MessagingException me){
                me.printStackTrace();
        }catch(IOException e) {
            e.printStackTrace();
        }

        if(isLove){
                System.out.println("Yes!She loves you!");
        }
        else{
                System.out.println("No!She doesn't love you!");
            }
        }

}
